package com.puyuba.puyuba.utils.custommessage;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMCustomMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.puyuba.puyuba.R;
import com.puyuba.puyuba.bean.SwapMobileBean;
import com.puyuba.puyuba.network.Constants;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.cache.SPHelper;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.puyuba.puyuba.network.UserApi;
import com.pyb.java.commonutil.ToastHelper;

import com.pyb.java.commonutil.eventbus.EventBusKeys;
import com.pyb.java.commonutil.eventbus.EventBusUtils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

public class ChatRowTxtNew extends EaseChatRow {
    private TextView contentView;
    private TextView tvDisagree;
    private TextView tvAgree;
    private TextView tvText;
    private LinearLayout llBottom;
    private String conversationId;
    private EMMessage showPhoneMessage;
    private String result;

    public ChatRowTxtNew(Context context, boolean isSender) {
        super(context, isSender);
    }

    @Override
    protected void onInflateView() {
        inflater.inflate(isSender ? R.layout.ease_row_sent_txt_new : R.layout.ease_row_received_txt_new, this);
    }

    @Override
    protected void onFindViewById() {
        contentView = (TextView) findViewById(R.id.tv_chatcontent);
        tvDisagree = (TextView) findViewById(R.id.tv_disagree);
        tvAgree = (TextView) findViewById(R.id.tv_agree);
        llBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        tvText = (TextView) findViewById(R.id.tv_text);
    }

    @Override
    protected void onSetUpView() {
        EMCustomMessageBody txtBody = (EMCustomMessageBody) message.getBody();
        Map<String,String> params = txtBody.getParams();
        String username = params.get(Constants.USER_NAME);
        String time = params.get(Constants.TIME);
        String type = params.get(Constants.TYPE);
        result = params.get(Constants.RESULT);

        //0 询问是否同意  1 一同意 2 不同意
        int flag =  SPHelper.getInt(time,1);
        if (flag == 1 ) {
            tvAgree.setText("已同意");
            tvAgree.setEnabled(false);
            tvAgree.setVisibility(VISIBLE);
            tvDisagree.setVisibility(GONE);
            tvAgree.setBackground(context.getResources().getDrawable(R.drawable.my_chat_bottom_agree_bg));
        }else if (flag ==2 ){
            tvAgree.setVisibility(GONE);
            tvDisagree.setVisibility(VISIBLE);
            tvDisagree.setEnabled(false);
            tvDisagree.setBackground(context.getResources().getDrawable(R.drawable.my_chat_bottom_disagree_bg));
        }else {
            tvAgree.setText("同意");
            tvDisagree.setText("不同意");
            tvAgree.setEnabled(true);
            tvDisagree.setEnabled(true);
            tvAgree.setVisibility(VISIBLE);
            tvDisagree.setVisibility(VISIBLE);
            tvAgree.setBackground(context.getResources().getDrawable(R.drawable.my_chat_bottom_right_bg));
            tvDisagree.setBackground(context.getResources().getDrawable(R.drawable.my_chat_bottom_left_bg));
        }
        if (type.equals("phone")){
            contentView.setText(username+"请求交换电话");
            tvText.setText("您已发送交换手机号邀请，等待对方答复");
        }else if (type.equals("zhiye")){
            contentView.setText(username+"邀请您填写职业成长需求");
            tvText.setText("您已发送评测邀请，等待对方答复");
        }else { //xueli
            contentView.setText(username+"邀请您填写学历提升需求");
            tvText.setText("您已发送评测邀请，等待对方答复");
        }

        tvDisagree.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (result.equals("none")){
                    SPHelper.putInt(time,2);
                    tvAgree.setVisibility(GONE);
                    tvDisagree.setBackground(context.getResources().getDrawable(R.drawable.my_chat_bottom_disagree_bg));
                    tvDisagree.setText("不同意");
                    if (type.equals("phone")){
                        sendPhoneMsg("对方拒绝交换手机号");
                    }else if (type.equals("zhiye")){
                        sendPhoneMsg("对方拒绝填写职业成长需求");
                    }else { //xueli
                        sendPhoneMsg("对方拒绝填写学历提升需求");
                    }
                    result = "no";
                }
            }
        });
        tvAgree.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (result.equals("none")){
                    tvDisagree.setVisibility(GONE);
                    SPHelper.putInt(time,1);
                    tvAgree.setBackground(context.getResources().getDrawable(R.drawable.my_chat_bottom_agree_bg));
                    tvAgree.setText("已同意");
                    result = "yes";
                    if (type.equals("phone")){
                        sendPhoneMsg("对方已同意交换手机号");
                        showPhone();//同意 发送交换电话弹窗
                    }else if (type.equals("zhiye")){
                        EventBusUtils.post(EventBusKeys.SHOW_ZHIYE);
                    }else {
                        EventBusUtils.post(EventBusKeys.SHOW_XUELI);
                    }
                }
            }
        });
    }
    //查询手机号交换信息
    public void swapmobile(int type,String other_uid,String uid,int change) {
        //type  1交换 0查询 默认0
        HashMap<String, Object> map = new HashMap<>();
        map.put("other_uid", other_uid);
        map.put("type", type);
        map.put("uid", uid);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);
        RetrofitManger.getInstance().createService(UserApi.class)
                .swapmobile(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<SwapMobileBean>>applySchedulers())
                .subscribe(new ResponseObserve<SwapMobileBean>(){

                    @Override
                    public void onSuccess(ResponseEntity<SwapMobileBean> responseEntity) {
                        //change 参数  是为了现在一方同意交换号码 另一方查询的时候还显示不同意 所以调了两次接口 避免重复展示数据
                        if (change == 1){
                            insertPhoneMsg(responseEntity.getData().getMobile(),conversationId);
                            EventBusUtils.post(EventBusKeys.REFRESH_MSG_LIST);
                        }
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@NonNull Disposable disposable) { }

                });
    }

    //本地插入显示手机号弹窗
    public void insertPhoneMsg(String phone,String name) {
        EMMessage phonemsg = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        EMCustomMessageBody phonebody = new EMCustomMessageBody(Constants.CHANGE_PHONE_CUSTOM_MSG);
        Map<String,String> params = new HashMap<>();
        params.put(Constants.PHONE,phone);
        params.put(Constants.USER_NAME,name);
        phonebody.setParams(params);
        phonemsg.addBody(phonebody);
        insertMsg(phonemsg);
    }

    //发送系统提示消息
    public void sendPhoneMsg(String hint){
        EMMessage systemMsg = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        systemMsg.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                deleteMsg(systemMsg);
            }

            @Override
            public void onError(int code, String error) { }

            @Override
            public void onProgress(int progress, String status) { }
        });
        // event为需要传递的自定义消息事件，比如礼物消息，可以设置event = "gift"
        EMCustomMessageBody systembody = new EMCustomMessageBody(Constants.INSERT_SYSTEM_MESSAGE_CUSTOM_MSG);
        Map<String,String> params = new HashMap<>();
        params.put(Constants.SYSTEM_HINT,hint);

        systembody.setParams(params);
        systemMsg.addBody(systembody);
        // to指另一方环信id（或者群组id，聊天室id）
        conversationId = SPHelper.getString("conversationId","");
        systemMsg.setTo(conversationId);
        EMClient.getInstance().chatManager().sendMessage(systemMsg);

    }

    //发送交换电话弹窗
    public void showPhone(){
        if (showPhoneMessage == null){
            showPhoneMessage = EMMessage.createSendMessage(EMMessage.Type.CUSTOM);
        }
        showPhoneMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                deleteMsg(showPhoneMessage);
                //本地插入消息 展示手机号
                swapmobile(1,conversationId, CacheUserInfo.getInstance().getHxUid(),1);
                swapmobile(1,CacheUserInfo.getInstance().getHxUid(),conversationId,2);
            }

            @Override
            public void onError(int code, String error) { }

            @Override
            public void onProgress(int progress, String status) { }
        });
        // event为需要传递的自定义消息事件，比如礼物消息，可以设置event = "gift"
        EMCustomMessageBody body = new EMCustomMessageBody(Constants.CHANGE_PHONE_CUSTOM_MSG);
        // params类型为Map<String, String>
        Map<String,String> params = new HashMap<>();
        params.put(Constants.PHONE, CacheUserInfo.getInstance().getsUserInfo().getUser().getMobile());
        body.setParams(params);
        showPhoneMessage.addBody(body);

        // to指另一方环信id（或者群组id，聊天室id）
        showPhoneMessage.setTo(conversationId);
        EMClient.getInstance().chatManager().sendMessage(showPhoneMessage);
//        chatFragment.chatLayout.sendMessage(showPhoneMessage);

    }


    //删除当前会话的某条聊天记录
    private void deleteMsg(EMMessage message){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        conversation.removeMessage(message.getMsgId());
    }
    //根据会话插入消息
    private void insertMsg(EMMessage msg){
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        conversation.insertMessage(msg);
    }



}
